﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Samples.ServiceHosting.StorageClient;
using Ciripescu_WebRole.Entities;
using System.Data.Services.Client;

namespace Ciripescu_WebRole.BL
{
    public class CommentManager
    {
        #region Public Methods

        public CommentManager()
        {
            m_svcContext             = new MyServiceContext();
            m_svcContext.RetryPolicy = RetryPolicies.RetryN(3, TimeSpan.FromSeconds(1));
        }

        /// <summary>
        /// Executa un query cu toate retry-urile si continuation token-urile necesare
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        public IEnumerable<Comment> DoQuery(IQueryable<Comment> q)
        {
            TableStorageDataServiceQuery<Comment> query = new TableStorageDataServiceQuery<Comment>(q as DataServiceQuery<Comment>);
            IEnumerable<Comment> queryResults = query.ExecuteAllWithRetries();            
            return queryResults;
        }

        public IEnumerable<Comment> DoQuery(IQueryable<Comment> q, int count)
        {
            //TableStorageDataServiceQuery<CiripCache> query = new TableStorageDataServiceQuery<CiripCache>(q as DataServiceQuery<CiripCache>);
            IEnumerable<Comment> queryResults = q.Take(count);
            return queryResults;
        }

        public Comment GetSingleComment(string userName, string rowKey)
        {
            try
            {
                return (DoQuery(from c in m_svcContext.Comment where c.PartitionKey == userName && c.RowKey == rowKey select c)).Single();
            }
            catch (InvalidOperationException)
            {
                // no items to return
                return null;
            }
            catch (Exception e)
            {
                // oare mai de ce se logheaza aici si mai sus nu? Las asa ca nu stiu care ii faza....
                Utils.WriteLog(EventLogName.Error, e.ToString());
                return null;
            }
        }

        public List<Comment> GetAllItems()
        {
            //return CiripCacheListToCiripList(DoQuery(from c in m_svcContext.CiripCache select c).ToList());
            CommentManager cm = new CommentManager();
            return DoQuery(from c in m_svcContext.Comment select c).ToList();
        }
        public static List<Comment> GetAllItemsStatic()
        {
            //return CiripCacheListToCiripList(DoQuery(from c in m_svcContext.CiripCache select c).ToList());
            CommentManager cm = new CommentManager();
            return cm.GetAllItems();
        }

        public IEnumerable<Comment> GetAllItems(string startFromRowKey)
        {
            //return CiripCacheListToCiripList(DoQuery(from c in m_svcContext.CiripCache where c.RowKey.CompareTo(startFromRowKey) > 0 select c).ToList());
            return DoQuery(from c in m_svcContext.Comment where c.RowKey.CompareTo(startFromRowKey) > 0 select c).ToList();
        }




        public void Delete(Comment itemToDelete)
        {
            m_svcContext.DeleteObject(itemToDelete);
            m_svcContext.SaveChanges();
        }

        public void DeleteWithoutQ(Comment itemToDelete)
        {
            if (itemToDelete.PartitionKey == null)
                itemToDelete.PartitionKey = "";
            m_svcContext.AttachTo(m_svcContext.CommentTableName, itemToDelete, "*");
            Delete(itemToDelete);
        }

        public void Commit()
        {
            m_svcContext.SaveChanges();
        }

        public void DeleteWithNoCommit(Comment itemToDelete)
        {
            m_svcContext.DeleteObject(itemToDelete);
        }

        /// <summary>
        /// Updates an existing item from the tables.
        /// </summary>
        /// <param name="item"></param>
        public void Save(Comment item)
        {
            m_svcContext.UpdateObject(item);
            m_svcContext.SaveChanges();
        }

        public void AttachAndSave(Comment item)
        {
            if (item.PartitionKey == null)
                item.PartitionKey = "";
            m_svcContext.AttachTo(m_svcContext.CommentTableName, item, "*");
            Save(item);
        }

        /// <summary>
        /// Insert a new item in the tables.
        /// </summary>
        /// <param name="newItem"></param>
        public void Insert(Comment newItem)
        {
            m_svcContext.AddObject(m_svcContext.CommentTableName, newItem);
            m_svcContext.SaveChanges();
        }

        

        #endregion 

        #region Private Methods

        private MyServiceContext m_svcContext = null;
        
        #endregion
    }
}
